from ..domain import QuestionGenerateRequest
from pathlib import Path
import os
from langchain.text_splitter import RecursiveCharacterTextSplitter
from  langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
import pandas as pd
from fastapi.responses import FileResponse,JSONResponse
import asyncio
import uuid
import os
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, status
import aiofiles
# 模拟会话验证（实际应连接数据库或Redis）
async def verify_session(session_id: str) -> bool:
    """验证会话有效性"""
    # 这里示例简单验证，实际应检查数据库
    #return len(session_id) == 36  # 假设session_id是UUID格式
    return True  # 假设session_id是UUID格式



class FileUpdateUtils:
    def __init__(self,session_id,files):
        self.UPLOAD_DIR = Path(r'./app/data')
        self.MAX_FILE_SIZE = 1024 * 1024 * 100  # 100MB
        self.ALLOWED_TYPES = {
            "image/jpeg",  # JPEG 图像
            "image/png",  # PNG 图像
            "application/pdf",  # PDF 文档
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",  # Word 文档
            "text/plain"  # 文本文件
        }
        self.files = files
        self.session_id = session_id
        self.UPLOAD_DIR = self.UPLOAD_DIR.joinpath(session_id)
        os.makedirs(self.UPLOAD_DIR, exist_ok=True)

    async def update(self):
        print(self.UPLOAD_DIR)
        try:
            error_list = []
            if len(self.files)==0:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="未选择文件"
                )
            # 验证会话
            if not await verify_session(self.session_id):
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="无效会话或未授权"
                )
            file_info = []
            for file in self.files:

                # 验证文件类型
                if file.content_type not in self.ALLOWED_TYPES:
                    error_list.append({'file_name':file.filename,"detail":"不支持的文件类型"})
                    continue

                # 验证文件大小
                file.file.seek(0, os.SEEK_END)
                file_size = file.file.tell()
                if file_size > self.MAX_FILE_SIZE:
                    error_list.append({'file_name': file.filename, "detail": f"文件大小超过限制 ({self.MAX_FILE_SIZE // 1024 // 1024}MB)"})
                    continue

                file.file.seek(0)

                # 生成安全文件名
                file_ext = os.path.splitext(file.filename)[1]
                safe_filename = f"{uuid.uuid4().hex}-{file_ext}"
                save_path = os.path.join(self.UPLOAD_DIR, safe_filename)

                # 异步写入文件
                async with aiofiles.open(save_path, "wb") as buffer:
                    while chunk := await file.read(1024 * 1024):  # 1MB分块读取
                        await buffer.write(chunk)

                file_info.append({
                    "saved_name": safe_filename,
                    "original_name": file.filename,
                    "content_type": file.content_type,
                    "preview_url": save_path,
                    "size": file_size,  # 添加文件大小

                })
            return JSONResponse(content={
                "data": file_info,
                "error_list": error_list,
                "status": "success"
            }, status_code=200)


        except HTTPException as he:
            raise he
        except Exception as e:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"文件上传失败: {str(e)}"
            )
